/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    int sumRootToLeaf(TreeNode *root)
    {
        return sumRootToLeaf(root, 0);
    }

    int sumRootToLeaf(TreeNode *tree, int prefix)
    {
        if (tree->left == nullptr && tree->right == nullptr)
        {
            return (prefix << 1) + tree->val;
        };

        int result = 0;
        prefix = (prefix << 1) + tree->val;
        if (tree->left != nullptr)
        {
            result += sumRootToLeaf(tree->left, prefix);
        }
        if (tree->right != nullptr)
        {
            result += sumRootToLeaf(tree->right, prefix);
        }
        return result;
    }
};